home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Misc Servers / Zope.exe / AQUEDUCT.PY < prev    next >
Encoding:
Python Source  |  2000-06-15  |  16.0 KB  |  469 lines

  1. 7##############################################################################
  2. # Zope Public License (ZPL) Version 1.0
  3. # -------------------------------------
  4. # Copyright (c) Digital Creations.  All rights reserved.
  5. # This license has been certified as Open Source(tm).
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions are
  8. # met:
  9. # 1. Redistributions in source code must retain the above copyright
  10. #    notice, this list of conditions, and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. #    notice, this list of conditions, and the following disclaimer in
  13. #    the documentation and/or other materials provided with the
  14. #    distribution.
  15. # 3. Digital Creations requests that attribution be given to Zope
  16. #    in any manner possible. Zope includes a "Powered by Zope"
  17. #    button that is installed by default. While it is not a license
  18. #    violation to remove this button, it is requested that the
  19. #    attribution remain. A significant investment has been put
  20. #    into Zope, and this effort will continue if the Zope community
  21. #    continues to grow. This is one way to assure that growth.
  22. # 4. All advertising materials and documentation mentioning
  23. #    features derived from or use of this software must display
  24. #    the following acknowledgement:
  25. #      "This product includes software developed by Digital Creations
  26. #      for use in the Z Object Publishing Environment
  27. #      (http://www.zope.org/)."
  28. #    In the event that the product being advertised includes an
  29. #    intact Zope distribution (with copyright and license included)
  30. #    then this clause is waived.
  31. # 5. Names associated with Zope or Digital Creations must not be used to
  32. #    endorse or promote products derived from this software without
  33. #    prior written permission from Digital Creations.
  34. # 6. Modified redistributions of any form whatsoever must retain
  35. #    the following acknowledgment:
  36. #      "This product includes software developed by Digital Creations
  37. #      for use in the Z Object Publishing Environment
  38. #      (http://www.zope.org/)."
  39. #    Intact (re-)distributions of any official Zope release do not
  40. #    require an external acknowledgement.
  41. # 7. Modifications are encouraged but must be packaged separately as
  42. #    patches to official Zope releases.  Distributions that do not
  43. #    clearly separate the patches from the original work must be clearly
  44. #    labeled as unofficial distributions.  Modifications which do not
  45. #    carry the name Zope may be packaged in any form, as long as they
  46. #    conform to all of the clauses above.
  47. # Disclaimer
  48. #   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
  49. #   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  50. #   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  51. #   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
  52. #   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  53. #   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  54. #   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  55. #   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  56. #   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  57. #   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  58. #   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  59. #   SUCH DAMAGE.
  60. # This software consists of contributions made by Digital Creations and
  61. # many individuals on behalf of Digital Creations.  Specific
  62. # attributions are listed in the accompanying credits file.
  63. ##############################################################################
  64. __doc__='''Shared classes and functions
  65.  
  66. $Id: Aqueduct.py,v 1.40.18.1 2000/06/15 21:56:23 amos Exp $'''
  67. __version__='$Revision: 1.40.18.1 $'[11:-2]
  68.  
  69. import Globals, os
  70. from Globals import HTMLFile, Persistent
  71. import DocumentTemplate, DateTime, ts_regex,  regex, string
  72. import binascii, Acquisition
  73. DateTime.now=DateTime.DateTime
  74. from cStringIO import StringIO
  75. from OFS import SimpleItem
  76. from AccessControl.Role import RoleManager
  77. from DocumentTemplate import HTML
  78.  
  79. from string import strip, replace
  80.  
  81. dtml_dir=Globals.package_home(globals())
  82.  
  83. InvalidParameter='Invalid Parameter'
  84.  
  85.  
  86. class BaseQuery(Persistent, SimpleItem.Item,
  87.                 Acquisition.Implicit, RoleManager):
  88.  
  89.     def query_year(self): return self.query_date.year()
  90.     def query_month(self): return self.query_date.month()
  91.     def query_day(self): return self.query_date.day()
  92.     query_date=DateTime.now()
  93.     manage_options=()
  94.  
  95.     def quoted_input(self): return quotedHTML(self.input_src)
  96.     def quoted_report(self): return quotedHTML(self.report_src)
  97.  
  98.     MissingArgumentError='Bad Request'
  99.  
  100.     def _convert(self): self._arg=parse(self.arguments_src)
  101.  
  102.     def _argdata(self, REQUEST):
  103.  
  104.         r={}
  105.  
  106.         try: args=self._arg
  107.         except:
  108.             self._convert()
  109.             args=self._arg
  110.  
  111.         id=self.id
  112.         missing=[]
  113.  
  114.         for name in args.keys():
  115.             idname="%s/%s" % (id, name)
  116.             try:
  117.                 r[name]=REQUEST[idname]
  118.             except:
  119.                 try: r[name]=REQUEST[name]
  120.                 except:
  121.                     arg=args[name]
  122.                     try: r[name]=arg['default']
  123.                     except:
  124.                         try:
  125.                             if not arg['optional']: missing.append(name)
  126.                         except: missing.append(name)
  127.                     
  128.         if missing:
  129.             raise self.MissingArgumentError, missing
  130.  
  131.         return r
  132.  
  133.     _col=None
  134.     _arg={}
  135.  
  136. class Searchable(BaseQuery):
  137.  
  138.     def _searchable_arguments(self):
  139.  
  140.         try: return self._arg
  141.         except:
  142.             self._convert()
  143.             return self._arg
  144.  
  145.     def _searchable_result_columns(self): return self._col
  146.  
  147.     def manage_testForm(self, REQUEST):
  148.         """Provide testing interface"""
  149.         input_src=default_input_form(self.title_or_id(),
  150.                                      self._searchable_arguments(),
  151.                                      'manage_test')
  152.         return HTML(input_src)(self, REQUEST)
  153.  
  154.     def manage_test(self, REQUEST):
  155.         'Perform an actual query'
  156.         
  157.         result=self(REQUEST)
  158.         report=HTML(custom_default_report(self.id, result))
  159.         return apply(report,(self,REQUEST),{self.id:result})
  160.  
  161.     def index_html(self, URL1):
  162.         " "
  163.         raise 'Redirect', ("%s/manage_testForm" % URL1)
  164.  
  165. class Composite:    
  166.  
  167.     def _getquery(self,id):
  168.  
  169.         o=self
  170.         i=0
  171.         while 1:
  172.             __traceback_info__=o
  173.             q=getattr(o,id)
  174.             try:
  175.                 if hasattr(q,'_searchable_arguments'):
  176.                     try: q=q.__of__(self.aq_parent)
  177.                     except: pass
  178.                     return q
  179.             except: pass
  180.             if i > 100: raise AttributeError, id
  181.             i=i+1
  182.             o=o.aq_parent
  183.             
  184.     def myQueryIds(self):
  185.         return map(
  186.             lambda k, queries=self.queries:
  187.             {'id': k, 'selected': k in queries},
  188.             self.ZQueryIds())
  189.  
  190. def default_input_form(id,arguments,action='query',
  191.                        tabs=''):
  192.     if arguments:
  193.         items=arguments.items()
  194.         return (
  195.             "%s\n%s%s" % (
  196.                 '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">\n'
  197.                 '<html lang="en"><head><title>%s Input Data</title></head>\n'
  198.                 '<body bgcolor="#FFFFFF" link="#000099" vlink="#555555">\n%s\n'
  199.                 '<form action="<dtml-var URL2>/<dtml-var id>/%s" '
  200.                 'method="get">\n'
  201.                 '<h2>%s Input Data</h2>\n'
  202.                 'Enter query parameters:<br>'
  203.                 '<table>\n'
  204.                 % (id, tabs, action,id),
  205.                 string.joinfields(
  206.                     map(
  207.                         lambda a:
  208.                         ('<tr> <th>%s</th>\n'
  209.                          '     <td><input name="%s"\n'
  210.                          '                width=30 value="%s">'
  211.                          '     </td></tr>'
  212.                          % (nicify(a[0]),
  213.                             (
  214.                                 a[1].has_key('type') and
  215.                                 ("%s:%s" % (a[0],a[1]['type'])) or
  216.                                 a[0]
  217.                                 ),
  218.                             a[1].has_key('default') and a[1]['default'] or ''
  219.                             ))
  220.                         , items
  221.                         ),
  222.                 '\n'),
  223.                 '\n<tr><td colspan=2 align=center>\n'
  224.                 '<input type="SUBMIT" name="SUBMIT" value="Submit Query">\n'
  225.                 '<dtml-if HTTP_REFERER>\n'
  226.                 '  <input type="SUBMIT" name="SUBMIT" value="Cancel">\n'
  227.                 '  <INPUT NAME="CANCEL_ACTION" TYPE="HIDDEN"\n'
  228.                 '         VALUE="<dtml-var HTTP_REFERER>">\n'
  229.                 '</dtml-if>\n'
  230.                 '</td></tr>\n</table>\n</form>\n</body>\n</html>\n'
  231.                 )
  232.             )
  233.     else:
  234.         return (
  235.             '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">\n'
  236.             '<html lang="en"><head><title>%s Input Data</title></head>\n'
  237.             '<body bgcolor="#FFFFFF" link="#000099" vlink="#555555">\n%s\n'
  238.             '<form action="<dtml-var URL2>/<dtml-var id>/%s" '
  239.             'method="get">\n'
  240.             '<h2>%s Input Data</h2>\n'
  241.             'This query requires no input.<p>\n'
  242.             '<input type="SUBMIT" name="SUBMIT" value="Submit Query">\n'
  243.             '<dtml-if HTTP_REFERER>\n'
  244.             '  <input type="SUBMIT" name="SUBMIT" value="Cancel">\n'
  245.             '  <INPUT NAME="CANCEL_ACTION" TYPE="HIDDEN"\n'
  246.             '         VALUE="<dtml-var HTTP_REFERER>">\n'
  247.             '</dtml-if>\n'
  248.             '</td></tr>\n</table>\n</form>\n</body>\n</html>\n'
  249.             % (id, tabs, action, id)
  250.             )
  251.  
  252.  
  253. custom_default_report_src=DocumentTemplate.File(
  254.     os.path.join(dtml_dir,'customDefaultReport.dtml'))
  255.  
  256. def custom_default_report(id, result, action='', no_table=0,
  257.                           goofy=regex.compile('[^a-zA-Z0-9_]').search
  258.                           ):
  259.     columns=result._searchable_result_columns()
  260.     __traceback_info__=columns
  261.     heading=('<tr>\n%s        </tr>' %
  262.                  string.joinfields(
  263.                      map(lambda c:
  264.                          '          <th>%s</th>\n' % nicify(c['name']),
  265.                          columns),
  266.                      ''
  267.                      )
  268.                  )
  269.  
  270.     if no_table: tr, _tr, td, _td, delim = '<p>', '</p>', '', '', ',\n'
  271.     else: tr, _tr, td, _td, delim = '<tr>', '</tr>', '<td>', '</td>', '\n'
  272.  
  273.     row=[]
  274.     for c in columns:
  275.         n=c['name']
  276.         if goofy(n) >= 0: n='expr="_[\'%s]"' % (`'"'+n`[2:])
  277.         row.append('          %s<dtml-var %s%s>%s'
  278.                    % (td,n,c['type']!='s' and ' null=""' or '',_td))
  279.  
  280.     row=('     %s\n%s\n        %s' % (tr,string.joinfields(row,delim), _tr))
  281.  
  282.     return custom_default_report_src(
  283.         id=id,heading=heading,row=row,action=action,no_table=no_table)
  284.  
  285. def detypify(arg):
  286.     l=string.find(arg,':')
  287.     if l > 0: arg=arg[:l]
  288.     return arg
  289.  
  290. def decode(input,output):
  291.     while 1:
  292.         line = input.readline()
  293.         if not line: break
  294.         s = binascii.a2b_base64(line[:-1])
  295.         output.write(s)
  296.  
  297. def decodestring(s):
  298.         f = StringIO(s)
  299.         g = StringIO()
  300.         decode(f, g)
  301.         return g.getvalue()
  302.  
  303. class Args:
  304.     def __init__(self, data, keys):
  305.         self._data=data
  306.         self._keys=keys
  307.  
  308.     def items(self):
  309.         return map(lambda k, d=self._data: (k,d[k]), self._keys)
  310.  
  311.     def values(self):
  312.         return map(lambda k, d=self._data: d[k], self._keys)
  313.  
  314.     def keys(self): return list(self._keys)
  315.     def has_key(self, key): return self._data.has_key(key)
  316.     def __getitem__(self, key): return self._data[key]
  317.     def __setitem__(self, key, v): self._data[key]=v
  318.     def __delitem__(self, key): del self._data[key]
  319.     def __len__(self): return len(self._data)
  320.  
  321. def parse(text,
  322.           result=None,
  323.           keys=None,
  324.           unparmre=ts_regex.compile(
  325.               '\([\0- ]*\([^\0- =\"]+\)\)'),
  326.           parmre=ts_regex.compile(
  327.               '\([\0- ]*\([^\0- =\"]+\)=\([^\0- =\"]+\)\)'),
  328.           qparmre=ts_regex.compile(
  329.               '\([\0- ]*\([^\0- =\"]+\)="\([^"]*\)\"\)'),
  330.           ):
  331.  
  332.     if result is None:
  333.         result = {}
  334.         keys=[]
  335.  
  336.     __traceback_info__=text
  337.  
  338.     ts_results = parmre.match_group(text, (1,2,3))
  339.     if ts_results:
  340.         start, grps = ts_results
  341.         name=grps[1]
  342.         value={'default':grps[2]}
  343.         l=len(grps[0])
  344.     else:
  345.         ts_results = qparmre.match_group(text, (1,2,3))
  346.         if ts_results:
  347.                 start, grps = ts_results
  348.                 name=grps[1]
  349.                 value={'default':grps[2]}
  350.                 l=len(grps[0])
  351.         else:
  352.             ts_results = unparmre.match_group(text, (1,2))
  353.             if ts_results:
  354.                 start, grps = ts_results
  355.                 name=grps[1]
  356.                 l=len(grps[0])
  357.                 value={}
  358.             else:
  359.                 if not text or not strip(text): return Args(result,keys)
  360.                 raise InvalidParameter, text
  361.  
  362.  
  363.     lt=string.find(name,':')
  364.     if lt > 0:
  365.         value['type']=name[lt+1:]
  366.         name=name[:lt]
  367.  
  368.     result[name]=value
  369.     keys.append(name)
  370.  
  371.     return parse(text[l:],result,keys)
  372.  
  373. def quotedHTML(text,
  374.                character_entities=(
  375.                    ('&', '&'),
  376.                    ("<", '<' ),
  377.                    (">", '>' ),
  378.                    ('"', '"'))): #"
  379.  
  380.  
  381.     for re,name in character_entities:
  382.         text=replace(text,re,name)
  383.  
  384.     return text
  385.  
  386. def nicify(name):
  387.     name=replace(string.strip(name), '_',' ')
  388.     return string.upper(name[:1])+name[1:]
  389.  
  390. def decapitate(html, RESPONSE=None,
  391.                header_re=ts_regex.compile(
  392.                    '\(\('
  393.                           '[^\0- <>:]+:[^\n]*\n'
  394.                       '\|'
  395.                           '[ \t]+[^\0- ][^\n]*\n'
  396.                    '\)+\)[ \t]*\n\([\0-\377]+\)'
  397.                    ),
  398.                space_re=ts_regex.compile('\([ \t]+\)'),
  399.                name_re=ts_regex.compile('\([^\0- <>:]+\):\([^\n]*\)'),
  400.                ):
  401.  
  402.  
  403.     ts_results = header_re.match_group(html, (1,3))
  404.     if not ts_results: return html
  405.  
  406.     headers, html = ts_results[1]
  407.  
  408.     headers=string.split(headers,'\n')
  409.  
  410.     i=1
  411.     while i < len(headers):
  412.         if not headers[i]:
  413.             del headers[i]
  414.         else:
  415.             ts_results = space_re.match_group(headers[i], (1,))
  416.             if ts_results:
  417.                 headers[i-1]="%s %s" % (headers[i-1],
  418.                                         headers[i][len(ts_reults[1]):])
  419.                 del headers[i]
  420.             else:
  421.                 i=i+1
  422.  
  423.     for i in range(len(headers)):
  424.         ts_results = name_re.match_group(headers[i], (1,2))
  425.         if ts_reults:
  426.             k, v = ts_reults[1]
  427.             v=string.strip(v)
  428.         else:
  429.             raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i])
  430.         RESPONSE.setHeader(k,v)
  431.  
  432.     return html
  433.  
  434.  
  435. def delimited_output(results,REQUEST,RESPONSE):
  436.     delim=REQUEST['output-delimiter']
  437.     try: output_type=REQUEST['output-type']
  438.     except: output_type='text/plain'
  439.     RESPONSE.setHeader('content-type', output_type)
  440.     join=string.join
  441.     return "%s\n%s\n" % (
  442.         join(results.names(),delim),
  443.         join(map(lambda row, delim=delim, join=join:
  444.                  join(map(str,row),delim),
  445.                  results),
  446.              '\n')
  447.         )
  448.